﻿#include "SLT_tool_pub.h"
#include "SL_asynFramePub.h"
#include "SL_tcpServer.h"
#include "SLT_tcpSender.h"

//请求
struct _demo_cmd_Req_st
{
	std::string  encryption;
	std::string  sessionid;
	AIGC_JSON_HELPER(encryption, sessionid)
};

//应答
class _demo_cmd_Resp_st
{
public:
	int   ret;
	std::string  sessionid;
	std::string  ret_msg;
	AIGC_JSON_HELPER(ret, sessionid, ret_msg)
};
class senderSession : public SLF_SessionBase
{
public:
	virtual void OnStart() {
		setTimer(1, 1000, false);
		SLTcpClientPtr client =  tcpserverSptr->createClient(); //创建socket
		m_senderSptr = SLT_getTcpClientSender(client, "127.0.0.1", 32204, true);  //创建sender

	}
	virtual void OnStop() {}
	virtual void OnMsgArrive(SLF_senderPtr& _sender, uint32_t srcSid, int msgid, SLF_sendMemBasePtr& _data)
	{
		m_senderSptr.reset(); //释放sender(自动释放socket)

		_demo_cmd_Resp_st resp;
		aigc::JsonHelper::JsonToObject2(resp, _data->getData());
		SLT_LOG_ERR("recv,msgid:%d,sessionid:%s,ret:%d", msgid, resp.sessionid.c_str(), resp.ret);
	}
	virtual void OnTimer(uint32_t timerID, int _intervalMs, bool periodic)
	{
		if (!m_senderSptr) {
			return;
		}
		setTimer(1,2000, false);
		send();
	}
	void send() {
		SLT_LOG_ERR("send msg");
		_demo_cmd_Req_st req;
		req.encryption = "test1";
		req.sessionid = "sessi1";
		std::string strJson;
		aigc::JsonHelper::ObjectToJson(req, strJson);
		SLF_sendMemBasePtr mem(new SLF_sendMemBase());
		mem->m_mem.add(strJson.c_str(), strJson.length() + 1);
		m_senderSptr->SLF_postMsg(0,9999, getSessID(), mem);
	}

	SLTcpServerStpr tcpserverSptr;
	SLT_TCPSenderPtr m_senderSptr;
};
//全局接收消息处理
void tcp_sender_callback(uint32_t _dstID, int msgid, uint32_t _srcID,
	SLF_sendMemBasePtr& _data, const SLF_senderPtr& _senderPtr, SLF_SessionBasePtr& _in_out_sessSptr)
{
	printf("tcp_sender_callback recv\n");
}
int main(int argc, char** argv)
{
	//使用通用sender进行tcp消息发送。client端
	SLT_logInit();
	SLF_init(1);

	SLT_setTcpRecvMsgCb(tcp_sender_callback);
	SLTcpServerStpr tcpserverSptr = sl_createTcpServer();
	tcpserverSptr->init(nullptr);
	tcpserverSptr->start();

	senderSession* psess = new senderSession();
	psess->tcpserverSptr = tcpserverSptr;
	SLF_addSession(SLF_SessionBasePtr(psess));

	printf("run success\n");
	getchar();
    return 0;
}